package com.zzx.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zzx.common.domain.CommonResult;
import com.zzx.pojo.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/10/4 11:05
 */
@Tag(name = "用户控制器", description = "用户模块")
@RestController
@RequestMapping("user")
public class UserController
{
    @Value("${easyshop.user-service-name}")
    private String userServiceName;

    @Resource
    private RestTemplate restTemplate;//提供多种便捷访问远程http服务的方法，简单的Restful服务模板~

    /**
     * userLogin
     *
     * @param user
     * @return
     */
    @Tag(name = "用户控制器")
    @HystrixCommand(commandKey = "userLogin",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixUserLogin"
    )
    @PostMapping("/userLogin")
    public CommonResult userLogin(@RequestBody User user)
    {
        return restTemplate.postForObject(userServiceName + "/user/login", user, CommonResult.class);
    }

    public CommonResult hystrixUserLogin(@RequestBody User user)
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }

    /**
     * getUserByUserid
     * @param userId
     * @return
     */
    @Tag(name = "用户控制器")
    @HystrixCommand(commandKey = "getUserByUserId",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixGetUserByUserId"
    )
    @GetMapping("getUserByUserId")
    public CommonResult getUserByUserId(@RequestParam("userId") Integer userId)
    {
        return restTemplate.getForObject(userServiceName + "/user/ getUserById/" + userId, CommonResult.class);
    }

    public CommonResult hystrixGetUserByUserId(@RequestParam("userId") Integer userId)
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }

}